package top.jacktgq.lock.jmm.visibility.twoPhaseTermination.v1;

import top.jacktgq.utils.LogUtils;
import top.jacktgq.utils.Sleeper;

/**
 * 
 * @Title: TwoPhaseTermination.java 
 * @Package top.jacktgq.lock.jmm.visibility 
 * @Description: 两阶段终止线程：使用isInterrupted()方法判断是否被应该退出
 * @author CandyWall   
 * @date 2020年11月2日 下午3:38:48 
 * @version V1.0
 */
public class Demo1 {
	public static void main(String[] args) {
		TwoPhaseTermination tpt = new TwoPhaseTermination();
		tpt.start();
		
		Sleeper.sleep(1);
		
		//停止监控线程
		tpt.stop();
	}
}

class TwoPhaseTermination {
	private Thread monitorThread;
	
	public void start() {
		monitorThread = new Thread(() -> {
			Thread currentThread = Thread.currentThread();
			while(true) {
				//是否被打断
				if(currentThread.isInterrupted()) {
					LogUtils.log("TwoPhaseTermination", "料理后事");
					break;
				}
				try {
					Thread.sleep(300);					
					LogUtils.log("TwoPhaseTermination", "执行监控记录");
				} catch (InterruptedException e) {
					e.printStackTrace();
					//因为sleep过程中被打断会抛出异常，然后会清除打断标记
					//所以需要重置打断标记
					currentThread.interrupt();
				}
			}
		}, "监控线程");
		monitorThread.start();
	}
	
	public void stop() {
		monitorThread.interrupt();
	}
}